package org.ellwood.core.utils;

import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: ellwood-boot-pro
 * @PackageName: org.ellwood.common.core
 * @ClassName: utils
 * @Description: // 数据拷贝工具类
 * @Author: Ellwood
 * @CreateDate: 2024/6/12 - 上午10:54
 * @Version: V1.0.0
 */
public class BeanCopyUtils {

    private static final ModelMapper modelMaper=new ModelMapper();

    public BeanCopyUtils() {
        throw new IllegalStateException("BeanCopyUtils class Illegal");
    }

    /**
     * 后续版本弃用，使用modelMapper实现，支持更加灵活
     * @param source  source
     * @param target target
     */
    @Deprecated
    public static <T, M> void springCopy(T source, M target) {
        BeanUtils.copyProperties(source, target);
    }

    /**
     * 后续版本弃用，使用modelMapper实现，支持更加灵活
     * @param source 资源
     * @param clazz 类
     */
    @Deprecated
    public static <T> T springCopy(Object source, Class<T> clazz) {
        T target = BeanUtils.instantiateClass(clazz);
        BeanUtils.copyProperties(source, target);
        return target;
    }

    /**
     *  modelMapper bean copy, 严格匹配模式 （属性名称与类型必须一致才进行复制）
     * @param source 属性名称
     * @param clazz 类
     * @return 返回复制结果
     * @param <T> 类型
     */
    public static <T> T copy(Object source,Class<T> clazz){
        ModelMapper mapper = new ModelMapper();
        mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return mapper.map(source,clazz);
    }

    /**
     * list 复制
     * @param sourceList 集合资源
     * @param targetClass 类
     * @return 返回list 复制结果
     * @param <Source> 资源
     * @param <Target> target
     */
    public static <Source,Target> List<Target> copyList(List<Source> sourceList,Class<Target> targetClass){
        return sourceList.stream().map(source->modelMaper.map(source,targetClass)).collect(Collectors.toList());
    }
}
